<template>
  <div class="product-info-page">
    <el-row :gutter="20">
      <!-- 左侧分类树 -->
      <el-col :span="6">
        <el-card class="category-card">
          <template #header>
            <div class="card-header">
              <span>商品分类</span>
              <div class="header-actions">
                <el-button size="small" type="success" @click="handleAddCategory" v-if="hasPerm('product:category:add')">
                  <el-icon><Plus/></el-icon>
                  新增分类
                </el-button>
                <el-button size="small" type="primary" @click="refreshCategoryTree">
                  <el-icon><Refresh/></el-icon>
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 分类搜索 -->
          <div class="search-container">
            <el-input
              v-model="categorySearchKeyword"
              placeholder="搜索分类名称"
              clearable
              @input="handleCategorySearch"
            >
              <template #prefix>
                <el-icon><Search/></el-icon>
              </template>
            </el-input>
          </div>
          
          <el-tree
            ref="categoryTreeRef"
            :data="filteredCategoryTree"
            :props="treeProps"
            node-key="id"
            highlight-current
            @node-click="handleCategoryClick"
            @node-contextmenu="handleCategoryContextMenu"
            :expand-on-click-node="false"
            :default-expanded-keys="[1]"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-icon><Folder/></el-icon>
                <span>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      
      <!-- 右侧商品列表 -->
      <el-col :span="18">
        <el-card class="product-card">
          <template #header>
            <div class="card-header">
              <span>{{ currentCategory ? `商品列表 - ${currentCategory.name}` : '商品列表' }}</span>
              <div class="header-actions">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索商品名称或编码"
                  style="width: 200px; margin-right: 10px"
                  clearable
                  @input="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search/></el-icon>
                  </template>
                </el-input>
                <el-select
                  v-model="searchStatus"
                  placeholder="选择状态"
                  style="width: 120px; margin-right: 10px"
                  clearable
                  @change="handleSearch"
                >
                  <el-option label="全部" value=""/>
                  <el-option label="上架" :value="1"/>
                  <el-option label="下架" :value="0"/>
                </el-select>
                <el-button @click="clearSearch">清除条件</el-button>
                <el-button @click="handleSelectAll" v-if="filteredProductList.length > 0">
                  {{ selectedProducts.length === filteredProductList.length ? '取消全选' : '全选' }}
                </el-button>
                <el-button type="success" @click="handleExport" v-if="hasPerm('product:info:export')">
                  <el-icon><Download/></el-icon>
                  导出商品
                </el-button>
                <el-button type="warning" @click="handleImport" v-if="hasPerm('product:info:import')">
                  <el-icon><Upload/></el-icon>
                  导入商品
                </el-button>
                <el-button type="primary" @click="handleAdd" v-if="hasPerm('product:info:add')">新增商品</el-button>
              </div>
            </div>
          </template>
          
          <el-table
            :data="filteredProductList"
            style="width: 100%"
            v-loading="loading"
            element-loading-text="加载中..."
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="id" label="ID" width="80"/>
            <el-table-column prop="productName" label="商品名称" width="200"/>
            <el-table-column prop="productCode" label="商品编码" width="150"/>
            <el-table-column prop="marketPrice" label="市场价" width="100">
              <template #default="scope">
                <span class="price">¥{{ scope.row.marketPrice || '0.00' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="safetyStock" label="安全库存" width="100"/>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="单位" width="80"/>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleView(scope.row)" v-if="hasPerm('product:info:view')">查看</el-button>
                <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-if="hasPerm('product:info:edit')">编辑</el-button>
                <el-button
                  size="small"
                  :type="scope.row.status === 1 ? 'warning' : 'success'"
                  @click="handleToggleStatus(scope.row)"
                  v-if="hasPerm('product:info:edit')"
                >
                  {{ scope.row.status === 1 ? '下架' : '上架' }}
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-if="hasPerm('product:info:delete')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 批量操作 -->
          <div class="batch-actions" v-if="selectedProducts.length > 0">
            <el-divider content-position="left">
              批量操作 (已选择 {{ selectedProducts.length }} 个商品)
            </el-divider>
            <div class="batch-buttons">
              <el-button
                type="success"
                size="small"
                @click="handleBatchOn"
                :loading="batchLoading"
              >
                <el-icon><Upload/></el-icon>
                批量上架 ({{ selectedProducts.length }})
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleBatchOff"
                :loading="batchLoading"
              >
                <el-icon><Download/></el-icon>
                批量下架 ({{ selectedProducts.length }})
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleBatchDelete"
                :loading="batchLoading"
              >
                <el-icon><Delete/></el-icon>
                批量删除 ({{ selectedProducts.length }})
              </el-button>
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 分类管理对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="categoryDialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item label="上级分类" prop="parentId">
          <!-- 尝试使用普通的选择器作为备选 -->
          <el-select
            v-model="categoryForm.parentId"
            placeholder="请选择上级分类"
            clearable
            style="width: 100%"
            @change="handleParentCategoryChange"
          >
            <el-option
              v-for="category in flatCategoryList"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            />
          </el-select>
          <!-- 调试信息 -->
          <div v-if="categoryTree.length === 0" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">
            暂无分类数据，请先添加根分类
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" placeholder="排序值"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm" :loading="categorySubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="productDetailVisible"
      title="商品详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="productDetail" class="product-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>商品编码：</label>
              <span>{{ productDetail.productCode || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>商品名称：</label>
              <span>{{ productDetail.productName }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>所属分类：</label>
              <span>{{ productDetail.categoryName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>计量单位：</label>
              <span>{{ productDetail.unitName }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>成本价：</label>
              <span class="price">¥{{ productDetail.costPrice || '0.00' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>市场价：</label>
              <span class="price">¥{{ productDetail.marketPrice || '0.00' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>安全库存：</label>
              <span>{{ productDetail.safetyStock || 0 }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>序列号管理：</label>
              <span>{{ productDetail.hasSerial === 1 ? '是' : '否' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>商品状态：</label>
              <el-tag :type="productDetail.status === 1 ? 'success' : 'danger'">
                {{ productDetail.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>创建人：</label>
              <span>{{ productDetail.author || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>创建时间：</label>
              <span>{{ formatDate(productDetail.createTime) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>更新时间：</label>
              <span>{{ formatDate(productDetail.updateTime) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row v-if="productDetail.imageUrl">
          <el-col :span="24">
            <div class="detail-item">
              <label>商品图片：</label>
              <div class="product-image">
                <el-image
                  :src="productDetail.imageUrl"
                  :preview-src-list="[productDetail.imageUrl]"
                  fit="cover"
                  style="width: 100px; height: 100px"
                />
              </div>
            </div>
          </el-col>
        </el-row>
        
        <el-row v-if="productDetail.remark">
          <el-col :span="24">
            <div class="detail-item">
              <label>备注：</label>
              <span>{{ productDetail.remark }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑商品对话框 -->
    <el-dialog
      v-model="productFormVisible"
      :title="productFormTitle"
      width="1200px"
      :close-on-click-modal="false"
      top="3vh"
      @close="handleProductFormClose"
      class="product-form-dialog"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="140px"
        class="product-form"
        size="large"
      >
        <!-- 基本信息 -->
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon"><Document /></el-icon>
                <span class="header-title">基本信息</span>
              </div>
              <div class="header-actions">
                <el-tag type="primary" effect="dark" size="small">必填信息</el-tag>
              </div>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="productName">
                <el-input 
                  v-model="productForm.productName" 
                  placeholder="请输入商品名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建人" prop="author">
                <el-input 
                  v-model="productForm.author" 
                  placeholder="请输入创建人"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属分类" prop="categoryId">
                <el-select
                  v-model="productForm.categoryId"
                  placeholder="请选择商品分类"
                  clearable
                  style="width: 100%"
                  :loading="loading"
                >
                  <el-option
                    v-for="category in flatCategoryList"
                    :key="category.id"
                    :label="category.categoryName"
                    :value="category.id"
                  />
                </el-select>
                <div v-if="categoryTree.length === 0" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">
                  暂无分类数据，请先添加分类
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认单位" prop="unitId">
                <el-select
                  v-model="productForm.unitId"
                  placeholder="请选择默认单位"
                  style="width: 100%"
                >
                  <el-option
                    v-for="unit in unitList"
                    :key="unit.id"
                    :label="unit.unitName"
                    :value="unit.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="成本价" prop="costPrice">
                <el-input-number
                  v-model="productForm.costPrice"
                  :precision="2"
                  :min="0"
                  :max="999999"
                  style="width: 100%"
                  placeholder="请输入成本价"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="市场价" prop="marketPrice">
                <el-input-number
                  v-model="productForm.marketPrice"
                  :precision="2"
                  :min="0"
                  :max="999999"
                  style="width: 100%"
                  placeholder="请输入市场价"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="安全库存" prop="safetyStock">
                <el-input-number
                  v-model="productForm.safetyStock"
                  :min="0"
                  :max="999999"
                  style="width: 100%"
                  placeholder="请输入安全库存"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="序列号管理" prop="hasSerial">
                <el-radio-group v-model="productForm.hasSerial">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品状态" prop="status">
                <el-radio-group v-model="productForm.status">
                  <el-radio :label="1">上架</el-radio>
                  <el-radio :label="0">下架</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input
                  v-model="productForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 商品图片 -->
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon"><Picture /></el-icon>
                <span class="header-title">商品图片</span>
              </div>
              <div class="header-actions">
                <el-tag type="success" effect="dark" size="small">可选信息</el-tag>
                <el-button size="small" type="primary" @click="handleAddImage" class="action-btn">
                  <el-icon><Plus/></el-icon>
                  添加图片
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="image-upload-container">
            <el-upload
              ref="imageUploadRef"
              :http-request="handleImageUpload"
              :before-upload="beforeImageUpload"
              :on-remove="onImageRemove"
              :on-change="handleImageChange"
              :file-list="productForm.images"
              list-type="picture-card"
              :limit="5"
              accept="image/*"
              :auto-upload="false"
              action="#"
              :show-file-list="true"
              class="image-upload"
            >
              <el-icon class="el-icon--upload"><Plus/></el-icon>
              <div class="el-upload__text">点击上传</div>
              <div class="el-upload__tip">支持 JPG、PNG、GIF 格式</div>
            </el-upload>
            
            <div class="upload-tips">
              <div class="tip-item">
                <el-icon><InfoFilled /></el-icon>
                <span>支持格式：JPG、PNG、GIF，单个文件不超过2MB</span>
              </div>
              <div class="tip-item">
                <el-icon><InfoFilled /></el-icon>
                <span>建议尺寸：800x800像素，最多上传5张图片</span>
              </div>
              <div class="tip-item">
                <el-icon><InfoFilled /></el-icon>
                <span>第一张图片将作为商品主图</span>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 多单位配置 -->
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon"><Box /></el-icon>
                <span class="header-title">多单位配置</span>
              </div>
              <div class="header-actions">
                <el-tag type="warning" effect="dark" size="small">可选配置</el-tag>
                <el-button size="small" type="primary" @click="handleAddUnit" class="action-btn">
                  <el-icon><Plus/></el-icon>
                  添加单位
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="unit-config-container">
            <el-table 
              :data="productForm.units" 
              style="width: 100%" 
              :key="'units-table-' + Date.now()"
              class="config-table"
              stripe
              border
            >
              <el-table-column prop="unitId" label="单位" width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.unitId"
                    placeholder="选择单位"
                    style="width: 100%"
                    @change="handleUnitChange(scope.$index)"
                  >
                    <el-option
                      v-for="unit in unitList"
                      :key="unit.id"
                      :label="unit.unitName"
                      :value="unit.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格" width="150">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.price"
                    :precision="2"
                    :min="0"
                    :max="999999"
                    style="width: 100%"
                    placeholder="价格"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存" width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.stock"
                    :min="0"
                    :max="999999"
                    style="width: 100%"
                    placeholder="库存"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="conversionRatio" label="换算比例" width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.conversionRatio"
                    :precision="2"
                    :min="0.01"
                    :max="999999"
                    style="width: 100%"
                    placeholder="比例"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="启用"
                    inactive-text="禁用"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleRemoveUnit(scope.$index)"
                    class="delete-btn"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
        
        <!-- 扩展信息 -->
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon"><Setting /></el-icon>
                <span class="header-title">扩展信息</span>
              </div>
              <div class="header-actions">
                <el-tag type="warning" effect="dark" size="small">可选配置</el-tag>
                <el-button size="small" type="primary" @click="handleAddAttribute" class="action-btn">
                  <el-icon><Plus/></el-icon>
                  添加属性
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="attribute-config-container">
            <el-table 
              :data="productForm.attributes" 
              style="width: 100%" 
              :key="'attributes-table-' + Date.now()"
              class="config-table"
              stripe
              border
            >
              <el-table-column prop="attrId" label="属性" width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.attrId"
                    placeholder="选择属性"
                    style="width: 100%"
                    @change="handleAttributeChange(scope.$index)"
                  >
                    <el-option
                      v-for="attr in attributeList"
                      :key="attr.id"
                      :label="attr.attrName"
                      :value="attr.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="attrValueId" label="属性值" width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.attrValueId"
                    placeholder="选择属性值"
                    style="width: 100%"
                    :disabled="!scope.row.attrId"
                    :loading="!getAttributeValues(scope.row.attrId).length && scope.row.attrId"
                  >
                    <el-option
                      v-for="value in getAttributeValues(scope.row.attrId)"
                      :key="value.id"
                      :label="value.attrValue"
                      :value="value.id"
                    />
                    <el-option
                      v-if="getAttributeValues(scope.row.attrId).length === 0 && scope.row.attrId"
                      label="暂无属性值"
                      value=""
                      disabled
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格" width="150">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.price"
                    :precision="2"
                    :min="0"
                    :max="999999"
                    style="width: 100%"
                    placeholder="价格"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存" width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.stock"
                    :min="0"
                    :max="999999"
                    style="width: 100%"
                    placeholder="库存"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="启用"
                    inactive-text="禁用"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleRemoveAttribute(scope.$index)"
                    class="delete-btn"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productFormVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="submitProductForm" :loading="productSubmitting" size="large">
            <el-icon v-if="!productSubmitting"><Check /></el-icon>
            {{ productSubmitting ? '保存中...' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入商品对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入商品"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-container">
        <el-upload
          ref="uploadRef"
          :action="uploadAction"
          :headers="uploadHeaders"
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          accept=".xlsx,.xls"
          drag
        >
          <el-icon class="el-icon--upload"><Upload/></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 xlsx/xls 文件，且不超过 10MB
            </div>
          </template>
        </el-upload>
        
        <div class="import-tips">
          <h4>导入说明：</h4>
          <ul>
            <li>请使用Excel文件格式(.xlsx或.xls)</li>
            <li>文件大小不超过10MB</li>
            <li>请按照模板格式填写数据</li>
            <li>商品编码不能重复</li>
            <li>分类ID必须是已存在的分类</li>
            <li>单位ID必须是已存在的单位</li>
          </ul>
        </div>
        
        <div class="template-download">
          <el-button type="text" @click="downloadTemplate">
            <el-icon><Download/></el-icon>
            下载导入模板
          </el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="importLoading">
            开始导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 右键菜单 -->
    <div
      v-show="contextMenuVisible"
      :style="contextMenuStyle"
      class="context-menu"
      @click="contextMenuVisible = false"
    >
      <div class="context-menu-item" @click="handleEditCategory">
        <el-icon><Edit/></el-icon>
        编辑分类
      </div>
      <div class="context-menu-item" @click="handleAddSubCategory">
        <el-icon><Plus/></el-icon>
        添加子分类
      </div>
      <div class="context-menu-item danger" @click="handleDeleteCategory">
        <el-icon><Delete/></el-icon>
        删除分类
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { hasPerm } from '@/utils/permission'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Folder, Search, Refresh, Plus, Edit, Delete, Upload, Download, Document, Picture, Box, Setting, InfoFilled, Check } from '@element-plus/icons-vue'
import {
  getCategoryTree,
  getProductsByCategory,
  getProductDetail,
  getProductFullDetail,
  deleteProduct,
  updateProductStatus,
  addProduct,
  updateProduct,
  addCategory,
  updateCategory,
  deleteCategory,
  getCategoryDetail,
  getAllUnits,
  getAttributeList
} from '@/api/product'
import { uploadImage, deleteFile } from '@/api/upload'

// 响应式数据
const categoryTree = ref([])
const productList = ref([])
const currentCategory = ref(null)
const loading = ref(false)
const searchKeyword = ref('')
const searchStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const categoryTreeRef = ref(null)
const categoryFormRef = ref(null)

// 分类管理相关
const categorySearchKeyword = ref('')
const categoryDialogVisible = ref(false)
const categoryDialogTitle = ref('新增分类')
const categorySubmitting = ref(false)
const contextMenuVisible = ref(false)
const contextMenuStyle = ref({})
const selectedCategory = ref(null)

// 商品详情相关
const productDetailVisible = ref(false)
const productDetail = ref(null)

// 批量操作相关
const selectedProducts = ref([])
const batchLoading = ref(false)

// 导入导出相关
const importDialogVisible = ref(false)
const importLoading = ref(false)
const uploadRef = ref(null)
const uploadAction = '/api/product/import'
const uploadHeaders = {}
const uploadData = {}

// 新增商品相关
const productFormVisible = ref(false)
const productFormTitle = ref('新增商品')
const productSubmitting = ref(false)
const productFormRef = ref(null)
const unitList = ref([])
const attributeList = ref([])
const attributeValueMap = ref({})

// 商品表单
const productForm = ref({
  id: null,
  productName: '',
  author: '',
  categoryId: null,
  unitId: null,
  costPrice: null,
  marketPrice: null,
  safetyStock: 0,
  hasSerial: 0,
  status: 1,
  remark: '',
  images: [],
  units: [],
  attributes: []
})

// 商品表单验证规则
const productRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '商品名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入创建人', trigger: 'blur' },
    { min: 2, max: 50, message: '创建人长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  unitId: [
    { required: true, message: '请选择默认单位', trigger: 'change' }
  ],
  costPrice: [
    { required: true, message: '请输入成本价', trigger: 'blur' }
  ],
  marketPrice: [
    { required: true, message: '请输入市场价', trigger: 'blur' }
  ],
  safetyStock: [
    { required: true, message: '请输入安全库存', trigger: 'blur' }
  ]
}

// 图片上传相关
const imageUploadRef = ref(null)
const imageUploadAction = '/api/upload/image'
const imageUploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}
const imageUploadData = {}

// 图片上传处理
const handleImageUpload = async (options) => {
  const { file, onSuccess, onError } = options
  
  console.log('开始上传图片:', file.name, file.size)
  console.log('请求URL:', 'http://localhost:8081/api/upload/image')
  
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    console.log('发送上传请求...')
    console.log('FormData内容:', formData)
    
    const response = await uploadImage(formData)
    console.log('上传响应:', response)
    
    if (response && response.code === 200) {
      // 检查是否已经存在相同的图片
      const existingIndex = productForm.value.images.findIndex(img => 
        img.name === file.name && img.size === file.size
      )
      
      if (existingIndex !== -1) {
        console.log('图片已存在，更新URL:', file.name)
        productForm.value.images[existingIndex].url = response.data
        onSuccess(productForm.value.images[existingIndex])
        ElMessage.success('图片上传成功')
        return
      }
      
      // 创建图片对象
      const imageObj = {
        uid: file.uid || Date.now() + Math.random(),
        name: file.name,
        url: response.data,
        status: 'success',
        size: file.size
      }
      
      console.log('创建图片对象:', imageObj)
      
      // 添加到表单的图片数组中
      productForm.value.images.push(imageObj)
      console.log('当前图片列表:', productForm.value.images)
      
      // 调用成功回调
      onSuccess(imageObj)
      ElMessage.success('图片上传成功')
    } else {
      throw new Error(response?.msg || '上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    console.error('错误详情:', error.response || error)
    ElMessage.error('图片上传失败: ' + error.message)
    onError(error)
  }
}

// 分类表单
const categoryForm = ref({
  id: null,
  categoryName: '',
  parentId: null,
  sort: 0,
  status: 1
})

// 分类表单验证规则
const categoryRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '分类名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 树形配置
const treeProps = {
  children: 'children',
  label: 'categoryName',
  value: 'id'
}

// 计算属性 - 过滤后的商品列表（现在直接使用后端返回的数据）
const filteredProductList = computed(() => {
  return productList.value
})

// 计算属性 - 过滤后的分类树
const filteredCategoryTree = computed(() => {
  if (!categorySearchKeyword.value) {
    return categoryTree.value
  }
  
  const filterTree = (nodes) => {
    return nodes.filter(node => {
      const match = node.categoryName.toLowerCase().includes(categorySearchKeyword.value.toLowerCase())
      if (node.children && node.children.length > 0) {
        node.children = filterTree(node.children)
        return match || node.children.length > 0
      }
      return match
    })
  }
  
  return filterTree(JSON.parse(JSON.stringify(categoryTree.value)))
})

// 计算属性 - 扁平化的分类列表（用于选择器）
const flatCategoryList = computed(() => {
  const result = []
  
  const flatten = (nodes, level = 0) => {
    nodes.forEach(node => {
      result.push({
        ...node,
        categoryName: '　'.repeat(level) + node.categoryName // 添加缩进
      })
      if (node.children && node.children.length > 0) {
        flatten(node.children, level + 1)
      }
    })
  }
  
  flatten(categoryTree.value)
  return result
})

// 获取分类树
const loadCategoryTree = async() => {
  try {
    loading.value = true
    const response = await getCategoryTree()
    
    if (response && response.code === 200) {
      // 处理不同的数据结构
      let treeData = response.data
      if (response.data && response.data.list) {
        treeData = response.data.list
      } else if (response.data && response.data.records) {
        treeData = response.data.records
      } else if (response.data && response.data.data) {
        treeData = response.data.data
        }
      
      categoryTree.value = treeData || []
    } else {
      categoryTree.value = []
    }
  } catch (error) {
    console.error('获取分类树失败:', error)
    ElMessage.error('获取分类树失败')
    categoryTree.value = []
  } finally {
    loading.value = false
  }
}

// 根据分类获取商品列表
const loadProductsByCategory = async(categoryId) => {
  if (!categoryId) return
  
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      productName: searchKeyword.value || undefined,
      status: searchStatus.value !== '' ? searchStatus.value : undefined
    }
    
    const response = await getProductsByCategory(categoryId, params)
    
    if (response && response.code === 200) {
      // PageInfo结构包含list和total等字段
      productList.value = response.data?.list || []
      total.value = response.data?.total || 0
      
      // 如果没有数据，检查是否有其他字段
      if (productList.value.length === 0 && response.data) {
        if (response.data.records) {
          productList.value = response.data.records
        } else if (response.data.data) {
          productList.value = response.data.data
        }
        if (response.data.total) {
          total.value = response.data.total
        }
      }
    } else {
      productList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
    productList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分类点击事件
const handleCategoryClick = (data) => {
  currentCategory.value = {
    id: data.id,
    name: data.categoryName // 使用categoryName作为显示名称
  }
  currentPage.value = 1
  loadProductsByCategory(data.id)
}

// 刷新分类树
const refreshCategoryTree = async () => {
  try {
    ElMessage.info('正在刷新分类树...')
    await loadCategoryTree()
    ElMessage.success('分类树刷新完成')
  } catch (error) {
    console.error('刷新分类树失败:', error)
    ElMessage.error('刷新分类树失败')
  }
}

// 分类搜索处理
const handleCategorySearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 搜索处理
const handleSearch = () => {
  // 重置到第一页
  currentPage.value = 1
  // 重新加载商品列表
  if (currentCategory.value) {
    loadProductsByCategory(currentCategory.value.id)
  }
}

// 清除搜索条件
const clearSearch = () => {
  searchKeyword.value = ''
  searchStatus.value = ''
  // 重置到第一页并重新加载
  currentPage.value = 1
  if (currentCategory.value) {
    loadProductsByCategory(currentCategory.value.id)
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  if (currentCategory.value) {
    loadProductsByCategory(currentCategory.value.id)
  }
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  if (currentCategory.value) {
    loadProductsByCategory(currentCategory.value.id)
  }
}

// 分类管理操作
const handleAddCategory = async() => {
  // 确保分类树数据是最新的
  await loadCategoryTree()
  
  categoryForm.value = {
    id: null,
    categoryName: '',
    parentId: null,
    sort: 0,
    status: 1
  }
  categoryDialogTitle.value = '新增分类'
  categoryDialogVisible.value = true
}

const handleEditCategory = async() => {
  if (!selectedCategory.value) return
  
  try {
    const response = await getCategoryDetail(selectedCategory.value.id)
    if (response && response.code === 200) {
      categoryForm.value = { ...response.data }
      categoryDialogTitle.value = '编辑分类'
      categoryDialogVisible.value = true
    } else {
      ElMessage.error('获取分类详情失败')
    }
  } catch (error) {
    console.error('获取分类详情失败:', error)
    ElMessage.error('获取分类详情失败')
  }
}

const handleAddSubCategory = async() => {
  if (!selectedCategory.value) return
  
  // 确保分类树数据是最新的
  await loadCategoryTree()
  
  categoryForm.value = {
    id: null,
    categoryName: '',
    parentId: selectedCategory.value.id,
    sort: 0,
    status: 1
  }
  categoryDialogTitle.value = '新增子分类'
  categoryDialogVisible.value = true
}

const handleDeleteCategory = async() => {
  if (!selectedCategory.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${selectedCategory.value.categoryName}"吗？删除后该分类下的所有商品将无法分类。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteCategory(selectedCategory.value.id)
    ElMessage.success('删除成功')
    loadCategoryTree()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleCategoryContextMenu = (event, data) => {
  event.preventDefault()
  selectedCategory.value = data
  contextMenuStyle.value = {
    left: event.clientX + 'px',
    top: event.clientY + 'px'
  }
  contextMenuVisible.value = true
}



const submitCategoryForm = async() => {
  try {
    await categoryFormRef.value.validate()
    categorySubmitting.value = true
    
    if (categoryForm.value.id) {
      // 编辑
      await updateCategory(categoryForm.value)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addCategory(categoryForm.value)
      ElMessage.success('新增成功')
    }
    
    categoryDialogVisible.value = false
    loadCategoryTree()
  } catch (error) {
    console.error('提交分类表单失败:', error)
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    categorySubmitting.value = false
  }
}

// 商品操作
const handleAdd = async () => {
  // 确保分类数据是最新的
  await loadCategoryTree()
  
  resetProductForm()
  // 如果当前有选中的分类，设置为默认分类
  if (currentCategory.value) {
    productForm.value.categoryId = currentCategory.value.id
  }
  productFormTitle.value = '新增商品'
  productFormVisible.value = true
}

// 重置商品表单
const resetProductForm = () => {
  productForm.value = {
    id: null,
    productName: '',
    author: '',
    categoryId: null,
    unitId: null,
    costPrice: null,
    marketPrice: null,
    safetyStock: 0,
    hasSerial: 0,
    status: 1,
    remark: '',
    images: [],
    units: [],
    attributes: []
  }
  if (productFormRef.value) {
    productFormRef.value.clearValidate()
  }
}

// 加载单位列表
const loadUnitList = async () => {
  try {
    const response = await getAllUnits()
    if (response && response.code === 200) {
      unitList.value = response.data || []
    }
  } catch (error) {
    console.error('获取单位列表失败:', error)
    ElMessage.error('获取单位列表失败')
  }
}

// 加载属性列表
const loadAttributeList = async () => {
  try {
    const response = await getAttributeList()
    
    if (response && response.code === 200) {
      // 处理新的数据结构
      const data = response.data || {}
      attributeList.value = data.list || []
      
      // 直接从属性列表中提取属性值
      if (attributeList.value.length > 0) {
        for (const attr of attributeList.value) {
          if (attr.attrValues && attr.attrValues.length > 0) {
            attributeValueMap.value[attr.id] = attr.attrValues
          } else {
            attributeValueMap.value[attr.id] = []
          }
        }
      }
    } else {
      ElMessage.error('获取属性列表失败')
    }
  } catch (error) {
    console.error('获取属性列表失败:', error)
    ElMessage.error('获取属性列表失败')
  }
}

// 获取属性值列表
const getAttributeValues = (attrId) => {
  if (!attrId) return []
  return attributeValueMap.value[attrId] || []
}



// 图片上传相关方法
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  
  // 检查是否已经上传过相同的文件
  const existingImage = productForm.value.images.find(img => 
    img.name === file.name && img.size === file.size
  )
  
  if (existingImage) {
    ElMessage.warning('该图片已经上传过了!')
    return false
  }
  
  return true
}

const onImageRemove = (file) => {
  console.log('开始删除图片:', file)
  
  // 如果有图片URL，调用后端删除API
  if (file.url) {
    console.log('调用后端删除API，URL:', file.url)
    
    // 调用删除API
    deleteFile(file.url).then(response => {
      if (response && response.code === 200) {
        console.log('后端删除成功')
        ElMessage.success('图片删除成功')
      } else {
        console.error('后端删除失败:', response)
        ElMessage.error('图片删除失败')
      }
    }).catch(error => {
      console.error('删除API调用失败:', error)
      console.error('错误详情:', error.response?.data || error.message)
      ElMessage.error('图片删除失败')
    })
  } else {
    console.warn('图片没有URL，跳过删除API调用')
  }
  
  // 从图片列表中移除
  const index = productForm.value.images.findIndex(img => img.uid === file.uid)
  if (index > -1) {
    productForm.value.images.splice(index, 1)
  }
  console.log('移除图片后，当前图片列表:', productForm.value.images)
}

const handleImageChange = (file, fileList) => {
  console.log('图片选择变化:', file, fileList)
  
  // 如果文件状态是ready，手动触发上传
  if (file.status === 'ready') {
    // 检查是否已经上传过相同的文件
    const existingImage = productForm.value.images.find(img => 
      img.name === file.name && img.size === file.size
    )
    
    if (existingImage) {
      console.log('文件已存在，跳过上传:', file.name)
      file.status = 'success'
      file.url = existingImage.url
      return
    }
    
    // 检查是否正在上传中
    if (file.status === 'uploading') {
      console.log('文件正在上传中，跳过:', file.name)
      return
    }
    
    console.log('手动触发上传...')
    file.status = 'uploading'
    
    handleImageUpload({
      file: file.raw,
      onSuccess: (imageObj) => {
        console.log('手动上传成功:', imageObj)
        // 更新文件状态和URL
        file.status = 'success'
        file.url = imageObj.url
        file.response = { data: imageObj.url }
        console.log('更新后的文件对象:', file)
      },
      onError: (error) => {
        console.error('手动上传失败:', error)
        file.status = 'error'
      }
    })
  }
}

const handleAddImage = () => {
  // 强制清理重复图片
  const uniqueImages = []
  const seen = new Set()
  
  productForm.value.images.forEach(img => {
    const key = `${img.name}-${img.size}`
    if (!seen.has(key)) {
      seen.add(key)
      uniqueImages.push(img)
    } else {
      console.log('移除重复图片:', img.name)
    }
  })
  
  productForm.value.images = uniqueImages
  console.log('清理后的图片列表:', productForm.value.images)
  
  // 强制更新el-upload的file-list
  if (imageUploadRef.value) {
    imageUploadRef.value.clearFiles()
    productForm.value.images.forEach(img => {
      imageUploadRef.value.handleStart(img)
    })
  }
  
  // 直接触发el-upload的文件选择
  if (imageUploadRef.value) {
    imageUploadRef.value.$el.querySelector('input').click()
  }
}

// 多单位配置相关方法
const handleAddUnit = () => {
  productForm.value.units.push({
    unitId: null,
    price: null,
    stock: 0,
    conversionRatio: 1,
    status: 1
  })
}

const handleRemoveUnit = (index) => {
  productForm.value.units.splice(index, 1)
}

// 单位选择变化处理
const handleUnitChange = (index) => {
  // 可以在这里添加单位变化的逻辑
  console.log('单位选择变化:', index, productForm.value.units[index])
}



// 扩展信息相关方法
const handleAddAttribute = () => {
  productForm.value.attributes.push({
    attrId: null,
    attrValueId: null,
    price: null,
    stock: 0,
    status: 1
  })
}

const handleRemoveAttribute = (index) => {
  productForm.value.attributes.splice(index, 1)
}

const handleAttributeChange = (index) => {
  const attrId = productForm.value.attributes[index].attrId
  
  // 清空属性值选择
  productForm.value.attributes[index].attrValueId = null
}







// 提交商品表单
const submitProductForm = async () => {
  try {
    await productFormRef.value.validate()
    productSubmitting.value = true
    
    // 验证多单位配置
    if (productForm.value.units.length > 0) {
      const invalidUnits = productForm.value.units.filter(unit => !unit.unitId || !unit.price)
      if (invalidUnits.length > 0) {
        ElMessage.error('请完善多单位配置信息')
        return
      }
    }
    
    // 验证扩展信息
    if (productForm.value.attributes.length > 0) {
      const invalidAttributes = productForm.value.attributes.filter(attr => !attr.attrId || !attr.attrValueId)
      if (invalidAttributes.length > 0) {
        ElMessage.error('请完善扩展信息配置')
        return
      }
    }
    
    // 准备提交数据
    const submitData = {
      ...productForm.value,
      imageUrl: productForm.value.images.length > 0 ? productForm.value.images[0].url : null,
      imageUrls: productForm.value.images.map(img => img.url),
      // 图片URL用逗号分隔
      imageUrlString: productForm.value.images.map(img => img.url).join(','),
      // 过滤掉空的多单位配置，使用extraUnits字段名
      extraUnits: productForm.value.units.filter(unit => unit.unitId && unit.price),
      // 过滤掉空的扩展信息配置
      attributes: productForm.value.attributes.filter(attr => attr.attrId && attr.attrValueId)
    }
    
    console.log('提交的数据:', submitData)
    console.log('多单位配置:', submitData.extraUnits)
    console.log('扩展信息:', submitData.attributes)
    
    if (productForm.value.id) {
      // 编辑
      await updateProduct(submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addProduct(submitData)
      ElMessage.success('新增成功')
    }
    
    productFormVisible.value = false
    
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } catch (error) {
    console.error('提交商品表单失败:', error)
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    productSubmitting.value = false
  }
}

// 商品表单对话框关闭处理
const handleProductFormClose = () => {
  // 重置表单
  resetProductForm()
  // 清除验证
  if (productFormRef.value) {
    productFormRef.value.clearValidate()
  }
}

// 导入导出处理
const handleImport = () => {
  importDialogVisible.value = true
}

const handleExport = async() => {
  try {
    const response = await fetch('/api/product/export', {
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || ''
      }
    })
    
    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `商品信息_${new Date().toISOString().slice(0, 10)}.xlsx`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      ElMessage.success('导出成功')
    } else {
      ElMessage.error('导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const downloadTemplate = async() => {
  try {
    const response = await fetch('/api/product/template', {
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || ''
      }
    })
    
    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '商品导入模板.xlsx'
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      ElMessage.success('模板下载成功')
    } else {
      ElMessage.error('模板下载失败')
    }
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败')
  }
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

const onUploadSuccess = (response, file) => {
  if (response.code === 200) {
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

const onUploadError = (error, file) => {
  console.error('上传失败:', error)
  ElMessage.error('导入失败')
}

const submitUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.submit()
  }
}

const handleView = async(row) => {
  try {
    const response = await getProductDetail(row.id)
    
    if (response && response.code === 200) {
      productDetail.value = response.data
      productDetailVisible.value = true
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

const handleEdit = async(row) => {
  try {
    // 确保分类数据是最新的
    await loadCategoryTree()
    
    const response = await getProductFullDetail(row.id)
    if (response && response.code === 200) {
      const productData = response.data
      
      console.log('编辑商品数据:', productData)
      console.log('商品图片数据:', productData.imageUrls)
      console.log('商品单位数据:', productData.extraUnits)
      console.log('商品属性数据:', productData.attributes)
      
      // 处理图片数据
      let images = []
      
      // 处理逗号分隔的图片URL
      if (productData.imageUrl && productData.imageUrl.includes(',')) {
        const imageUrls = productData.imageUrl.split(',').filter(url => url.trim())
        imageUrls.forEach((url, index) => {
          images.push({
            uid: Date.now() + index,
            name: `product-image-${index}.jpg`,
            url: url.trim(),
            status: 'success'
          })
        })
      } else if (productData.imageUrl) {
        // 单个图片URL
        images.push({
          uid: Date.now(),
          name: 'product-image.jpg',
          url: productData.imageUrl,
          status: 'success'
        })
      }
      
      // 处理imageUrls数组
      if (productData.imageUrls && productData.imageUrls.length > 0) {
        productData.imageUrls.forEach((url, index) => {
          // 避免重复添加
          const existingImage = images.find(img => img.url === url)
          if (!existingImage) {
            images.push({
              uid: Date.now() + 1000 + index,
              name: `product-image-${index}.jpg`,
              url: url,
              status: 'success'
            })
          }
        })
      }
      
      // 处理多单位数据
      let units = []
      if (productData.extraUnits && productData.extraUnits.length > 0) {
        units = productData.extraUnits.map(unit => ({
          unitId: unit.unitId,
          price: unit.price,
          stock: unit.stock || 0,
          conversionRatio: unit.conversionRatio || 1,
          status: unit.status || 1
        }))
      }
      
      // 处理扩展属性数据
      let attributes = []
      if (productData.attributes && productData.attributes.length > 0) {
        attributes = productData.attributes.map(attr => ({
          attrId: attr.attrId,
          attrValueId: attr.attrValueId,
          price: attr.price || 0,
          stock: attr.stock || 0,
          status: attr.status || 1
        }))
      }
      
      // 设置表单数据
      productForm.value = {
        id: productData.id,
        productName: productData.productName,
        author: productData.author || '',
        categoryId: productData.categoryId,
        unitId: productData.unitId,
        costPrice: productData.costPrice,
        marketPrice: productData.marketPrice,
        safetyStock: productData.safetyStock || 0,
        hasSerial: productData.hasSerial || 0,
        status: productData.status || 1,
        remark: productData.remark || '',
        images: images,
        units: units,
        attributes: attributes
      }
      
      console.log('设置后的表单数据:', productForm.value)
      console.log('设置后的单位数据:', productForm.value.units)
      console.log('设置后的属性数据:', productForm.value.attributes)
      
      productFormTitle.value = '编辑商品'
      productFormVisible.value = true
      
      // 强制更新表格渲染
      nextTick(() => {
        console.log('强制更新后的单位数据:', productForm.value.units)
        console.log('强制更新后的属性数据:', productForm.value.attributes)
      })
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 批量操作处理
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection
}

const handleSelectAll = () => {
  if (selectedProducts.value.length === filteredProductList.value.length) {
    // 取消全选
    selectedProducts.value = []
  } else {
    // 全选
    selectedProducts.value = [...filteredProductList.value]
  }
}

const handleBatchOn = async() => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要上架的商品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要上架选中的 ${selectedProducts.value.length} 个商品吗？`,
      '确认上架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    batchLoading.value = true
    const promises = selectedProducts.value.map(product =>
      updateProductStatus(product.id, 1)
    )
    
    await Promise.all(promises)
    ElMessage.success('批量上架成功')
    
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量上架失败')
    }
  } finally {
    batchLoading.value = false
  }
}

const handleBatchOff = async() => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要下架的商品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要下架选中的 ${selectedProducts.value.length} 个商品吗？`,
      '确认下架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    batchLoading.value = true
    const promises = selectedProducts.value.map(product =>
      updateProductStatus(product.id, 0)
    )
    
    await Promise.all(promises)
    ElMessage.success('批量下架成功')
    
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量下架失败')
    }
  } finally {
    batchLoading.value = false
  }
}

const handleBatchDelete = async() => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedProducts.value.length} 个商品吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    batchLoading.value = true
    const promises = selectedProducts.value.map(product =>
      deleteProduct(product.id)
    )
    
    await Promise.all(promises)
    ElMessage.success('批量删除成功')
    
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    batchLoading.value = false
  }
}

const handleToggleStatus = async(row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '上架' : '下架'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}商品"${row.productName}"吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateProductStatus(row.id, newStatus)
    ElMessage.success(`${action}成功`)
    
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleDelete = async(row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${row.productName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteProduct(row.id)
    ElMessage.success('删除成功')
    
    // 重新加载商品列表
    if (currentCategory.value) {
      loadProductsByCategory(currentCategory.value.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  loadCategoryTree()
  loadUnitList()
  loadAttributeList()
  
  // 点击外部关闭右键菜单
  document.addEventListener('click', () => {
    contextMenuVisible.value = false
  })
})
</script>

<style scoped>
.product-info-page {
  padding: 20px;
}

.category-card {
  height: calc(100vh - 140px);
  overflow: hidden;
}

.product-card {
  height: calc(100vh - 140px);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-container {
  margin-bottom: 15px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.category-count {
  color: #909399;
  font-size: 12px;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 3000;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.context-menu-item:hover {
  background-color: #f5f7fa;
}

.context-menu-item.danger {
  color: #f56c6c;
}

.context-menu-item.danger:hover {
  background-color: #fef0f0;
}

.price {
  color: #e6a23c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 树形组件样式 */
:deep(.el-tree-node__content) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

/* 多选列样式 */
:deep(.el-table .el-table__cell.is-center) {
  text-align: center;
}

:deep(.el-table .el-checkbox) {
  margin: 0;
}

/* 卡片样式 */
:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 商品详情样式 */
.product-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
  margin-right: 10px;
}

.detail-item span {
  color: #303133;
}

.product-image {
  margin-top: 10px;
}

/* 批量操作样式 */
.batch-actions {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.batch-buttons .el-button {
  margin: 0;
}

/* 导入导出样式 */
.import-container {
  padding: 20px 0;
}

.import-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.import-tips h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 14px;
}

.import-tips ul {
  margin: 0;
  padding-left: 20px;
}

.import-tips li {
  margin-bottom: 5px;
  color: #606266;
  font-size: 13px;
}

.template-download {
  margin-top: 15px;
  text-align: center;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

/* 新增商品表单样式 */
.product-form {
  max-height: 75vh;
  overflow-y: auto;
  padding: 0 10px;
}

.product-form-dialog {
  border-radius: 12px;
}

.product-form-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px 24px;
}

.product-form-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.product-form-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

.product-form-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: #f8fafc;
}

.product-form-dialog :deep(.el-dialog__footer) {
  background: white;
  border-top: 1px solid #e5e7eb;
  padding: 16px 24px;
  border-radius: 0 0 12px 12px;
}

.form-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.form-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.form-card:last-child {
  margin-bottom: 0;
}

.form-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-bottom: 1px solid #e5e7eb;
  padding: 16px 20px;
  border-radius: 12px 12px 0 0;
}

.form-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #1e293b;
}

.form-card .header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-card .header-icon {
  color: #3b82f6;
  font-size: 18px;
}

.form-card .header-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.form-card .header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.form-card .action-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.form-card .action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.image-upload-container {
  padding: 20px 0;
}

.image-upload :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  border: 2px dashed #d1d5db;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  transition: all 0.3s ease;
}

.image-upload :deep(.el-upload--picture-card:hover) {
  border-color: #3b82f6;
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  transform: translateY(-2px);
}

.image-upload :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

.image-upload :deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  border-radius: 12px;
}

.upload-tips {
  margin-top: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 12px;
  border: 1px solid #bae6fd;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #0369a1;
  font-size: 13px;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-item .el-icon {
  color: #0ea5e9;
  font-size: 14px;
}

.unit-config-container,
.attribute-config-container {
  padding: 16px 0;
}

.config-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.config-table :deep(.el-table__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.config-table :deep(.el-table__header th) {
  background: transparent;
  color: #1e293b;
  font-weight: 600;
  border-bottom: 2px solid #e5e7eb;
}

.config-table :deep(.el-table__body tr:hover) {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

.config-table :deep(.el-table__body td) {
  border-bottom: 1px solid #f1f5f9;
}

.delete-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

/* 表格内组件样式 */
.config-table :deep(.el-input-number) {
  width: 100%;
}

.config-table :deep(.el-select) {
  width: 100%;
}

.config-table :deep(.el-switch) {
  margin: 0;
}

.config-table :deep(.el-input-number .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.config-table :deep(.el-input-number .el-input__wrapper:hover) {
  border-color: #3b82f6;
}

.config-table :deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.config-table :deep(.el-select .el-input__wrapper:hover) {
  border-color: #3b82f6;
}

/* 图片上传组件样式 */
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

/* 选择器样式 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-tree-select) {
  width: 100%;
}



/* 对话框样式优化 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer .el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}

.dialog-footer .el-button:hover {
  transform: translateY(-1px);
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.dialog-footer .el-button--primary:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}

.dialog-footer .el-button--default {
  background: white;
  border: 1px solid #d1d5db;
  color: #374151;
}

.dialog-footer .el-button--default:hover {
  border-color: #9ca3af;
  background: #f9fafb;
}
</style>
